// wx.request封装
// const appInstance = getApp();
// 默认配置
let defaultOptions = {
  method: "GET",
  header: {
    'content-type': 'application/json' // 默认值
  },
};
// 失败返回一个 初始状态的promise
let alwasPending = new Promise(() => {})
const baseUrl = "http://127.0.0.1:1314";

function http(options, withLoding = true) {
  options.url = baseUrl + options.url;

  if (withLoding) wx.showLoading({
    title: '加载中...',
  });
  options = Object.assign({}, defaultOptions, options);
  // 请求服务器是要携带token
  options.header.authorization = wx.getStorageSync('token');
  return new Promise((resolve, reject) => {
    var reqTask = wx.request({
      ...options,
      success: (result) => {
        let {
          code,
          data,
          msg
        } = result.data;
        switch (code) {
          case 200:
            // 判断服务器是否返回token --- 没用到
            if (result.header.authorization) {
              wx.setStorageSync({
                key: 'token',
                data: result.header.authorization
              })
            }
            resolve(data);
            break;
          case 401:
            // appInstance.login();
            wx.login({
              timeout: 10000,
              success: async (result) => {
                console.log(result.code);
                const token = await http({
                  url: "/user/login/" + result.code
                });
                wx.setStorageSync('token', token)
              },
              fail: () => {},
              complete: () => {}
            });
            break;
          default:
            wx.showToast({
              title: msg,
              icon: 'none',
              duration: 1500,
              mask: false
            });
            return alwasPending;
        }
      },
      fail: (err) => {
        console.log(ererr);
        return alwasPending;
      },
      complete: () => {
        if (withLoding) wx.hideLoading({
          success: (res) => {},
        });

      }
    });

  })
}
module.exports = http;